<?php

namespace App\Http\Controllers\Innerend;

use App\Models\Fangtan;
use App\Models\FangtanAppoint;
use App\Models\FangtanUser;
use App\Models\Fresh;
use App\Models\User;


class FangtanFreshController extends BaseController
{
    // 访谈
    public function initialize()
    {
        parent::initialize();

        $fangtan_id = $this->getData('fangtan_id', 0, 'intval');
        $channel    = $this->getData('channel', '', 'trim');
        $url        = url('/innerend/fangtan-fresh/lists?fangtan_id='.$fangtan_id.'&channel='.$channel);

        $this->assign('init_url', $url);
        $this->model = 'Fresh';
    }

    // 详情中的访谈列表
    public function interview()
    {
        $result = $this->getFreshList('interview');

        return $this->success($result);
    }

    // 解答
    public function answer()
    {
        $result = $this->getFreshList('answer');

        return $this->success($result);
    }


    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        $userDb = new User();
        $uids   = array_column($lists, 'uid');
        $users  = $userDb->isCache(true)->getListInIds($uids);

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_uid  = $item['uid'];
            $_user = $users[$_uid] ?? [];
            $_id   = $item['id'];
            //$status   = $item['status'] == 1 ? '正常' : '禁用';
            //$topOp  = $item['is_top'] == 1 ? '取消置顶' : '置顶';
            //$param  = ['id' => $_id, 'is_top' => 1 - $item['is_top']];
            $is_complain = $item['is_complain'] == 1 ? '是' : '否';

            // 操作
            //$operate = $listHtml->operate_status($param, $topOp, $item['is_top'], 'to-top');
            $operate = '';
            //$operate .= $listHtml->operate_edit(['id' => $_id], '编辑');
            $operate .= $listHtml->operate_soft_delete(['id' => $_id], '你确定要删除该文章吗？');

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($item['title']);
            $tr .= $listHtml->list_td($_user['username']);
            $tr .= $listHtml->list_td($item['content']);
            $tr .= $listHtml->list_td($item['ip']);
            $tr .= $listHtml->list_td($item['ip_address']);
            $tr .= $listHtml->list_td($is_complain);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        return ['title' => ['标题', 200], 'uid' => ['用户', 80], 'content' => ['内容', 350], 'ip' => 'ip', 'ip_address' => '地址', 'is_complain' => ['是否投诉', 60], 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
    }

    // 列表搜索
    protected function list_search()
    {
        $request = $this->getData();
        $form    = $this->adminList();
        $keyword = $form->formInput('keyword', $request['keyword'] ?? '', '关键字');
        $datemin = $form->formDateTime('datemin', $request['datemin'] ?? '', '开始时间', 'datetime');
        $datemax = $form->formDateTime('datemax', $request['datemax'] ?? '', '结束时间', 'datetime');

        $search = ['keyword' => $keyword, 'datemin' => $datemin, 'datemax' => $datemax,];  // 'is_top' => $is_top,
        $this->assign('search', []);

        $searchHide = ['is_online', 'fangtan_id',];
        $this->assign('searchHide', $searchHide);
    }


    // 列表顶部按钮
    protected function listTopButton()
    {
        $addUrl     = url('/innerend/'.$this->controller.'/add');
        $top_button = '<a href="javascript:;" onclick="onEdit(\''.$addUrl.'\')" class="btn btn-success radius">添加</a> ';
        $this->assign('top_button', '');
    }


    // 软删除
    public function onSoft()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneEdit($where, ['verify' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();

        // 默认一张图片
        if(empty($info['images'])){
            $_images = ["", "", ""];
        } else{
            $_images = json_decode($info['images'], true);
            $count   = count($_images);
            for($ii = 0; $ii < 3 - $count; $ii++){
                $_images[] = '';
            }
        }
        // 多个图片
        $images = '';
        foreach($_images as $image){
            $images .= $form->formShowImage($image);
        }

        $fangtanId = $this->getData('fangtan_id', 0, 'intval');
        $channel   = $this->getData('channel', 'fangtan', 'trim');  // 类型（访谈:fangtan 问:ask 答:answer）

        $title       = $form->formInput('title', $info['title'] ?? '', '标题');
        $username    = $form->ajaxSearch('uid', $info['uid'] ?? '', 'User');
        $ip          = $form->formShow($info['ip'] ?? '127.0.0.1');
        $ip_address  = $form->formShow($info['ip_address'] ?? '本地');
        $fangtan_id  = $form->formShow($info['fangtan_id'] ?? $fangtanId);
        $content     = $form->formUeditor('content', $info['content'] ?? '');
        $is_complain = $form->formShow(empty($info['is_complain']) ? '否' : '是');
        $_id         = $form->formHidden('id', $info['id'] ?? '');
        $itype       = $form->formShow($info['itype'] ?? $channel);

        $html .= $form->makeItem('标题', $title);
        $html .= $form->makeItem('编辑', $username);
        $html .= $form->makeItem('访谈id', $fangtan_id);
        $html .= $form->makeItem('是否投诉', $is_complain);
        $html .= $form->makeItem('ip', $ip);
        $html .= $form->makeItem('地址', $ip_address);
        $html .= $form->makeItem('图片', $images);
        $html .= $form->makeItem('内容', $content);
        $html .= $_id;

        return $html;
    }


    // 发长短文
    public function publish()
    {
        $images    = $this->getData('images', [], 'is_array');
        $parent_id = $this->getData('parent_id', 0, 'intval');  // 回答的时候选择
        $fangtanId = $this->getData('fangtan_id', 0, 'intval');
        $to_uid    = $this->getData('to_uid', [], 'is_array');
        $uid       = $this->getData('uid', 0, 'intval'); // 发消息的人
        $is_draft  = $this->getData('is_draft', 0, 'intval');
        $itype     = $this->getData('itype', 'fangtan', 'trim'); // 类型（访谈:fangtan 问:ask 答:answer）
        $content   = $this->getData('content', '', 'trim');
        $this->throwIf(empty($content), '请填写转发内容!');
        $this->throwIf(empty($fangtanId), '请指定访谈编号!');
        $this->throwIf(!in_array($itype, ['fangtan', 'answer', 'ask']), '请指定访谈编号!');
        $this->throwIf(count($images) != count($images, 1), '请传递正确图片地址！');

        // TODO 判断是否禁言
        $myInfo = $this->getFangtanUser($fangtanId, $uid, 'no_speaking');
        $this->throwIf($myInfo, '对不起，您选择的用户被禁止发言!');
        $myInfo = $this->getFangtanUser($fangtanId, $uid, 'no_jion');
        $this->throwIf($myInfo, '对不起，您选择的用户已经被踢出!');
        // 如果是访谈，只有嘉宾才能操作
        if($itype == 'fangtan'){
            $myInfo = $this->getFangtanUser($fangtanId, $uid, 'guest');
            $this->throwIf($myInfo, '对不起，您选择的用户不是嘉宾!');
        }

        // 发送消息的频率
        //$freshDb = new Fresh();
        //$where   = [["uid", '=', $this->myUid], ["ctime", '>', LARAVEL_TIME - 60 * 60]];
        //$nums    = $freshDb->where($where)->count();
        //$this->throwIf($nums >= 3, '你发送消息太频繁，请休息下再来！!');

        // 审核转发内容
        //$spam = antispam($content);
        //$this->throwIf(empty($spam), '含有不符合内容!!');

        // TODO 提取的话题与阿特的用户需要独立出来 （添加修改，与列表详情都需要使用）
        // TODO 提取阿特用户
        // TODO 提取话题
        // "<text data-id='143' data-type='1' class='test'>#测试话题#</text>";
        // 如果是草稿 则不提取，因为修改的时候不方便
        $freshData = $this->getData4Fresh($content, $is_draft);
        $uids      = $freshData['uids'];
        $topids    = $freshData['topids'];

        // TODO 提取图片
        if(empty($images)){
            $images = $this->getImage4content($content);
        }
        // TODO 审核
        $this->baiduTextCensor($content);

        // 数据
        $ip   = $this->request->ip();
        $data = [
            'uid'        => $uid,
            'news_id'    => 0,
            'to_uid'     => json_encode($to_uid),
            'fangtan_id' => $fangtanId,
            'content'    => $content,
            'images'     => json_encode($images),
            'title'      => '',
            'is_short'   => 1,
            'verify'     => 1,
            'is_draft'   => $is_draft,
            'itype'      => $itype,
            'read_power' => 0,
            'ip'         => $ip,
            'ip_address' => $this->getIpAddress($ip),
            //'parent_id'  => $parent_id,

            // 修改的时候的字段
            // 'id'          => $this->id,
            // 'is_complain' => 0,
        ];
        // TODO 问题的父级是回答（父级不存在，且回答成问问题的父级）
        if($itype != 'answer'){
            $data['parent_id'] = $parent_id;
        }
        $freshDb = new Fresh();
        $id      = $freshDb->publish($uid, $data, $topids, $uids);
        $this->throwIf($id === false, $freshDb->getError());
        // TODO 问题的父级是回答（回答成问问题的父级）
        if($parent_id && ($itype == 'answer')){
            $freshDb->oneEdit(['id' => $parent_id], ['parent_id' => $id]);
        }

        // 获取金币
        // $this->addGold('fresh_short');

        return $this->success($id, '发布成功！');
    }


    // 发长短文
    public function _onEdit()
    {
        $images    = $this->getData('images', [], 'is_array');
        $parent_id = $this->getData('parent_id', 0, 'intval');  // 回答的时候选择
        $fangtanId = $this->getData('fangtan_id', 0, 'intval');
        $to_uid    = $this->getData('to_uid', [], 'is_array');
        $uid       = $this->getData('uid', 0, 'intval'); // 发消息的人
        $is_draft  = $this->getData('is_draft', 0, 'intval');
        $itype     = $this->getData('itype', 'fangtan', 'trim');  // 类型（访谈:fangtan 问:ask 答:answer）
        $content   = $this->getData('content', '', 'trim');
        $this->throwIf(empty($this->id), '请填写修改记录的编号!');
        $this->throwIf(empty($content), '请填写转发内容!');
        $this->throwIf(empty($fangtanId), '请指定访谈编号!');
        $this->throwIf(!in_array($itype, ['fangtan', 'answer', 'ask']), '请指定访谈编号!');
        $this->throwIf(count($images) != count($images, 1), '请传递正确图片地址！');

        // TODO 判断是否禁言
        $myInfo = $this->getFangtanUser($fangtanId, $uid, 'no_speaking');
        $this->throwIf($myInfo, '对不起，您选择的用户被禁止发言!');
        $myInfo = $this->getFangtanUser($fangtanId, $uid, 'no_jion');
        $this->throwIf($myInfo, '对不起，您选择的用户已经被踢出!');
        // 如果是访谈，只有嘉宾才能操作
        if($itype == 'fangtan'){
            $myInfo = $this->getFangtanUser($fangtanId, $uid, 'guest');
            $this->throwIf(empty($myInfo), '对不起，您选择的用户不是嘉宾!');
        }

        // 发送消息的频率
        //$freshDb = new Fresh();
        //$where   = [["uid", '=', $this->myUid], ["ctime", '>', LARAVEL_TIME - 60 * 60]];
        //$nums    = $freshDb->where($where)->count();
        //$this->throwIf($nums >= 3, '你发送消息太频繁，请休息下再来！!');

        // 审核转发内容
        //$spam = antispam($content);
        //$this->throwIf(empty($spam), '含有不符合内容!!');

        // TODO 提取的话题与阿特的用户需要独立出来 （添加修改，与列表详情都需要使用）
        // TODO 提取阿特用户
        // TODO 提取话题
        // "<text data-id='143' data-type='1' class='test'>#测试话题#</text>";
        // 如果是草稿 则不提取，因为修改的时候不方便
        $freshData = $this->getData4Fresh($content, $is_draft);
        $uids      = $freshData['uids'];
        $topids    = $freshData['topids'];

        // TODO 提取图片
        if(empty($images)){
            $images = $this->getImage4content($content);
        }
        // TODO 审核
        $this->baiduTextCensor($content);

        // 数据
        $data = [
            'uid'         => $uid,
            'news_id'     => 0,
            'to_uid'      => json_encode($to_uid),
            'fangtan_id'  => $fangtanId,
            'content'     => $content,
            'images'      => json_encode($images),
            'title'       => '',
            'is_short'    => 1,
            'verify'      => 1,
            'is_draft'    => $is_draft,
            'itype'       => $itype,
            'read_power'  => 0,
            'ip'          => $this->request->ip(),
            //'parent_id'  => $parent_id,

            // 修改的时候的字段
            'id'          => $this->id,
            'is_complain' => 0,
        ];
        // TODO 问题的父级是回答（父级不存在，且回答成问问题的父级）
        if($itype != 'answer'){
            $data['parent_id'] = $parent_id;
        }
        // 执行修改
        $freshDb = new Fresh();
        $id      = $freshDb->onEdit($uid, $data, $topids, $uids);
        $this->throwIf($id === false, $freshDb->getError());
        // TODO 问题的父级是回答（回答成问问题的父级）
        if($parent_id && ($itype == 'answer')){
            // 查找以前的父级（改为0）
            $freshDb->oneEdit(['parent_id' => $id], ['parent_id' => 0]);
            // 设置现在的父级
            $freshDb->oneEdit(['id' => $parent_id], ['parent_id' => $id]);
        }

        // 获取金币
        // $this->addGold('fresh_short');

        return $this->success($id, '发布成功！');
    }


    // 删除（软删除）
    public function onDel()
    {
        $fangtanId = $this->getData('fangtan_id', 0, 'intval');
        $fresh_id  = $this->getData('fresh_id', 0, 'intval');
        $this->throwIf(empty($fangtanId), '请指定访谈编号!');
        $this->throwIf(empty($fresh_id), '请指定你要删除的记录!');

        $freshDb = new Fresh();
        $where   = ['fangtan_id' => $fangtanId, 'id' => $fresh_id];
        $result  = $freshDb->oneEdit($where, ['verify' => -1]);
        $this->throwIf($result === false, $freshDb->getError());

        return $this->success([], '删除成功！！');
    }

    // 禁止发言，踢出
    public function onProhibit()
    {
        $fangtanId = $this->getData('fangtan_id', 0, 'intval');
        $itype     = $this->getData('itype', '', 'trim'); // no_jion no_speaking
        $uid       = $this->getData('uid', 0, 'intval');
        $this->throwIf(empty($fangtanId), '请指定访谈编号!');
        $this->throwIf(empty($uid), '请指定你要禁止的用户!');
        $this->throwIf(!in_array($itype, ['no_jion', 'no_speaking']), '错误的操作!');

        // 判断用户是否已经被禁用
        $fUserDb = new FangtanUser();
        $where   = ['fangtan_id' => $fangtanId, 'uid' => $uid, 'itype' => $itype];
        $info    = $fUserDb->oneFind($where);
        $this->throwIf(!empty($info['status']), '该用户已经被禁止!');

        // 保存数据
        if(empty($info)){
            $data = ['fangtan_id' => $fangtanId, 'uid' => $uid, 'itype' => $itype, 'status' => 1];
            $fUserDb->fill($data);
            $result = $fUserDb->save();
        } else{
            $result = $fUserDb->where('id', $info['id'])->update(['status' => 1]);
        }
        $this->throwIf($result === false, $fUserDb->getError());

        // 删除缓存
        $fUserDb->deleteCacheShow($info, $data ?? $where);
        $message = 'no_speaking' ? '禁言用户成功！！' : '踢出用户成功！！';

        return $this->success([], $message);
    }

    // 解除禁言，解除踢出
    public function cancleProhibit()
    {
        $fangtanId = $this->getData('fangtan_id', 0, 'intval');
        $itype     = $this->getData('itype', '', 'trim'); // no_jion no_speaking
        $uid       = $this->getData('uid', 0, 'intval');
        $this->throwIf(empty($fangtanId), '请指定访谈编号!');
        $this->throwIf(empty($uid), '请指定你要禁止的用户!');
        $this->throwIf(!in_array($itype, ['no_jion', 'no_speaking']), '错误的操作!');

        // 判断用户是否已经被禁用
        $fUserDb = new FangtanUser();
        $where   = ['fangtan_id' => $fangtanId, 'uid' => $uid, 'itype' => $itype, 'status' => 1];
        $info    = $fUserDb->oneFind($where);
        $this->throwIf(empty($info), '没有找到你要的操作记录!');

        // 保存数据
        $result = $fUserDb->where('id', $info['id'])->update(['status' => 0]);
        $this->throwIf($result === false, $fUserDb->getError());
        // 删除缓存
        $fUserDb->deleteCacheShow($info, ['status' => 0]);
        $message = 'no_speaking' ? '取消禁言用户操作成功！！' : '取消踢出用户操作成功！！';

        return $this->success([], $message);
    }

    // 查询
    // 列表查询
    protected function listWhere()
    {
        // 判断
        $channel    = $this->getData('channel', 'answer', 'intval');
        $fangtan_id = $this->getData('fangtan_id', 0, 'intval');
        $this->throwIf(empty($fangtan_id), '请指定需要操作的访谈！');
        // 条件
        if('answer' == $channel){
            $where = [['fangtan_id', '=', $fangtan_id], ['verify', '=', 1], ['read_power', '=', 0], ['is_complain', '=', 0], ['itype', '=', 'ask'],];
            /*$whereIn = function($qq) {
                $qq = $qq->whereIn('itype', ['answer', 'ask']);
            };*/
        } elseif('interview' == $channel){
            $where = [['fangtan_id', '=', $fangtan_id], ['verify', '=', 1], ['read_power', '=', 0], ['is_complain', '=', 0], ['itype', '=', 'fangtan'],];
        }

        return $where;
    }

    ######################################################################################################

    // 获取长短文
    protected function getFreshList($type)
    {
        $rows    = $this->rows;
        $page    = $this->page;
        $order   = "id DESC";
        $whereIn = null;


        // 缓存
        $freshDb   = new Fresh();
        $args      = compact('fangtan_id', 'page', 'rows', 'order', 'type');
        $cacheName = $freshDb->cacheKey('interview', $args);
        $cacheData = $freshDb->cacheClass()->getCache($cacheName);
        if(!empty($cacheData)){
            return $cacheData;
        }

        // 查询
        $query = $freshDb->where($where);
        if($whereIn){
            $query = $query->where($whereIn);
        }
        // 执行
        $count = $query->count();
        $lists = $query->forPage($page, $rows)->orderByRaw($order)->get()->toArray();
        $lists = $this->makeFreshListResult($lists, $fangtan_id);  // 结果整理（发布人的信息，阿特人的信息，话题信息，引用的父级）

        // 查看是否需要翻页
        $is_next = 0;
        if($page * $rows < $count){
            $is_next = 1;
        }

        // 保存为缓存
        $result = ['channel' => 'fresh', "total" => $count, 'page' => $page, 'rows' => $rows, 'is_next' => $is_next, "list" => $lists,];
        $freshDb->bangField(['fangtan_id'])->addCacheList($lists, $cacheName, $result, 'list');

        return $result;
    }

    // 获取访谈里面的用户信息
    protected function getFangtanUser($fangtan_id, $myUid, $type = 'host')
    {
        if(empty($myUid)){
            return [];
        }
        $fUserDb = new FangtanUser();
        // 查询
        $where = ['fangtan_id' => $fangtan_id, 'uid' => $myUid, 'itype' => $type, 'status' => 1];
        $info  = $fUserDb->isCache(true)->oneFind($where);
        $info  = is_object($info) ? $info->toArray() : $info;

        return $info;
    }
}



